#include "../include/Cell.h"

using namespace godot;

void Cell::_register_methods() {
	register_property<Cell, unsigned short>("state", &Cell::_set_state, &Cell::_get_state, 0);
	register_signal<Cell>("updateHistory", "index", Variant::Type::INT);
	
	register_method("setup", &Cell::setup);
	register_method("_toggle", &Cell::_toggle);
	register_method("_untoggle", &Cell::_untoggle);
	register_method("_ready", &Cell::_ready);
	register_method("_on_Cell_button_up", &Cell::_on_Cell_button_up);
	register_method("_on_Cell_button_down", &Cell::_on_Cell_button_down);
	register_method("_on_Cell_pressed", &Cell::_on_Cell_pressed);
}

void Cell::_init() {

}
void Cell::_ready() {
	get_node<Label>("Label")->set_text(std::to_string(value).c_str());
	connect("button_up", this, "_on_Cell_button_up");
	connect("button_down", this, "_on_Cell_button_down");
	connect("pressed", this, "_on_Cell_pressed");
}

void Cell::setup(const unsigned short value, const unsigned short index) {
	this->value = value;
	this->index = index;
}

void Cell::_on_Cell_button_up() {
	__reset_position();
}
void Cell::_on_Cell_button_down() {
	__change_position();
}
void Cell::_on_Cell_pressed() {
	get_tree()->get_root()->get_node("Root")->call("_play_click2");
	_toggle();
	call("emit_signal", "updateHistory", index);
}
void Cell::_set_state(const unsigned short state) {
	this->state = state;
}
unsigned short Cell::_get_state() {
	return state;
}

void Cell::_untoggle() {
	_set_state((_get_state()+2)%3);
	__change_color();
	grab_focus();
}
void Cell::_toggle() {
	_set_state((_get_state()+1)%3);
	__change_color();
	grab_focus();
}

void Cell::__change_color() {
	real_t offset;
	Color color, outline;
	switch(state) {
		case 1: {
			offset = 80;
			color = Color(0, 0.75, 0);
			outline = Color(0, 0.5, 0, 1);
			break;
		}
		case 2: {
			offset = 160;
			color = Color(0, 0, 1);
			outline = Color(0, 0, 0.5, 1);
			break;
		}
		default: {
			offset = 0;
			color = Color(1, 1, 1);
			outline = Color(1, 1, 1, 0.5);
			break;
		}
	}
	((AtlasTexture*)(get_normal_texture().ptr()))->set_region(Rect2(offset, 0, 40, 40));
	((AtlasTexture*)(get_pressed_texture().ptr()))->set_region(Rect2(offset+40, 0, 40, 40));
	get_node<Label>("Label")->add_color_override("font_color", color);
	get_node<Label>("Label")->add_color_override("font_outline_modulate", outline);
}
void Cell::__change_position() {
	get_node<Label>("Label")->_set_position(Vector2(1, 1));
}
void Cell::__reset_position() {
	get_node<Label>("Label")->_set_position(Vector2(0, 0));
}